#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
import ConfigParser
from optparse import OptionParser

from hparser import *

class ClusterConfig:
    """
    cluster config manager.
    """
    def __init__(self, home_dir, cluster_name):
        self.home_dir     = home_dir
        self.cluster_name = cluster_name
        self.conf         = {}

        config = ConfigParser.RawConfigParser()
        config.read('%s/hadoop-test/clusters.cfg' % self.home_dir)

        self.conf['cluster_id']        = config.getint(cluster_name, 'cluster_id')
        self.conf['lock_server_host']  = config.get(cluster_name, 'lock_server_host')
        self.conf['lock_server_port']  = config.getint(cluster_name, 'lock_server_port')
        self.conf['ssh_username']      = config.get(cluster_name, 'ssh_username')
        self.conf['ssh_server']        = config.get(cluster_name, 'ssh_server')

        self.conf['cluster_home_dir']  = '%s/%s' % (home_dir, cluster_name)
        self.conf['cluster_share_dir'] = '%s/hadoop-test/share/%s' % (home_dir, cluster_name)

    def get_masters(self):
        return [y for y in [l.strip(' \t\n') for l in open('%s/conf/masters' % self.conf['cluster_home_dir'])] if y]

    def get_slaves(self):
        return [y for y in [l.strip(' \t\n') for l in open('%s/conf/slaves' % self.conf['cluster_home_dir'])] if y]

    def get_clients(self):
        return [y for y in [l.strip(' \t\n') for l in open('%s/conf/clients' % self.conf['cluster_home_dir'])] if y]

    def __repr__(self):
        ret = ''

        ret += '******cluster config******\n'
        for k in sorted(self.conf.keys()):
            ret += '%45s <--> %s\n' % (k, str(self.conf[k]))

        ret += '\n'
        ret += '******core-site.xml******\n'
        site_file = '%s/conf/core-site.xml' % self.conf['cluster_home_dir']
        parser = HadoopSiteParser(site_file)

        items = [
                'hadoop.logfile.size',
                'dfs.namenode.logging.level',
                'fs.default.name', 
                'fs.checkpoint.period',
                'io.file.buffer.size',
                'io.bytes.per.checksum',
                'local.cache.size',
                ]
        for i in items:
            ret += '%45s <--> %s\n' % (i, parser.get(i))
        ret += '\n'

        ret += '******hdfs-site.xml******\n'
        site_file = '%s/conf/hdfs-site.xml' % self.conf['cluster_home_dir']
        parser = HadoopSiteParser(site_file)

        items = [
                'dfs.namenode.handler.count', 
                'dfs.datanode.handler.count',
                'dfs.name.dir',
                'dfs.data.dir',
                'dfs.blockreport.intervalMsec',
                'dfs.blockreport.initialDelay',
                'dfs.heartbeat.interval',
                'dfs.replication',
                'dfs.replication.min',
                'dfs.replication.max',
                'dfs.replication.interval',
                'dfs.block.size', 
                'dfs.client.block.write.retries',
                ]
        for i in items:
            ret += '%45s <--> %s\n' % (i, parser.get(i))


        ret += '\n'
        ret += '******masters******\n'
        masters = self.get_masters()
        for i, l in enumerate(masters):
            ret += '%45d <--> %s\n' % (i+1, l)

        ret += '\n'
        ret += '******slaves******\n'
        slaves = self.get_slaves()
        for i, l in enumerate(slaves):
            ret += '%45d <--> %s\n' % (i+1, l)

        ret += '\n'
        ret += '******clients******\n'
        clients = self.get_clients()
        for i, l in enumerate(clients):
            ret += '%45d <--> %s\n' % (i+1, l)
        return ret

if __name__ == "__main__":
    """ self-test """ 
    parser = OptionParser()
    parser.add_option("-H", "--htest",    dest="home_dir",     type='string', default="/share/home/testhdp")
    parser.add_option("-c", "--cluster",  dest="cluster_name", type='string', default="cluster1")
    (options, args) = parser.parse_args()

    conf = ClusterConfig(options.home_dir, options.cluster_name)
    print conf
